import React, { Component } from 'react'
import "./index.css"

// 传统作法：props
/* export default class A extends Component {

  state = {
    username: 'tom'
  }

  render() {
    return (
      <div className='parent'>
        <h3>我是A组件</h3>
        <h4>我的用户名是：{this.state.username}</h4>
        <B username={this.state.username}></B>
      </div>
    )
  }
}

class B extends Component {
  render() {
    return (
      <div className='child'>
        <h3>我是B组件</h3>
        <h4>我从A组件接收到的用户名：{this.props.username}</h4>
        <C username={this.props.username}></C>
      </div>
    )
  }
}

class C extends Component {
  render() {
    return (
      <div className='grand'>
        <h3>我是C组件</h3>
        <h4>我从A组件接收到的用户名：{this.props.username}</h4>
      </div>
    )
  }
} */

// 创建Context对象
const MyContext = React.createContext()
const {Provider, Consumer} = MyContext

export default class A extends Component {

  state = {
    username: 'tom',
    age: 18
  }

  render() {
    const {username, age} = this.state
    return (
      <div className='parent'>
        <h3>我是A组件</h3>
        <h4>我的用户名是：{username}</h4>
        <Provider value={{username, age}}>
          <B></B>
        </Provider>
      </div>
    )
  }
}

class B extends Component {
  render() {
    return (
      <div className='child'>
        <h3>我是B组件</h3>
        <h4>我从A组件接收到的用户名：{this.props.username}</h4>
        <C></C>
      </div>
    )
  }
}

// 类组件引用
/* class C extends Component {
  static contextType = MyContext
  render() {
    console.log(this.context);
    const {username, age} = this.context
    return (
      <div className='grand'>
        <h3>我是C组件</h3>
        <h4>我从A组件接收到的用户名：{username}，年龄是：{age}</h4>
      </div>
    )
  }
} */

// 函数式组件引用
function C () {
  return (
    <div className='grand'>
      <h3>我是C组件</h3>
      <h4>我从A组件接收到的用户名：
        <Consumer>
          {
            value => {
              const {username, age} = value
              return `${username}，年龄是：${age}`
            }
          }
        </Consumer>
      </h4>
    </div>
  )
}
